import redis
import requests
from flask import make_response, redirect
from flask_restful import reqparse
from tools.my_jwt import jj
from tools.captcha.captcha import captcha
from tools.comm.comm import sendMsg
from tools.myredis import r
from application.models.users.user import SfLogin
from application.models.users.user import *
from db import db
import json
import time
import random
from application.models.users.user import User
from flask import Blueprint,request,jsonify
good_blue = Blueprint("goodblue",__name__)

# 获取训练营里面得所有数据

@good_blue.route('/getxly')
def getxly():
    sql = 'select * from tcourse'
    res = db.find_all(sql)
    return jsonify({'code':200,'msg':'ok','data':res})

# 加入购物车
@good_blue.route('/addgood',methods=["POST"])
def addshop():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['userid'],args['id']}):
        return jsonify({'code':400,'msg':'数据不存在'})

    cart = Cart.query.filter(Cart.id == id).first()
    print(cart)
    if cart:
        sql = "update Cart set count=count+1 where cart.id=%d"%int(args['id'])
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'ok'})
    else:
        count = 1
        sql = "insert into cart(userid,cid,count) values('%d','%d','%d')"%(int(args['userid']),int(args['id']),int(count))
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'加入购物车成功'})

# 展示购物车数据
@good_blue.route('/getcourse')
def gettcourse():
    uid = request.args.get('userid')
    print(uid,'//////////////////////')
    list = []
    sql = "select * from cart where cart.userid=%d"% int(uid)
    res = db.find_all(sql)
    print('1111',res)
    for i in res:
        sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
        res1 = db.find_all(sql1)
        for j in res1:
            list.append({
                'id':j['id'],
                'title':j['title'],
                'price':j['price'],
                'count':i['count'],
                'url':j['url'],
                'amount':(j['price'] * i['count'])
            })
    return jsonify({'code':200,'msg':'ok','data':list})

# 生成订单
@good_blue.route('/addorder',methods=['POST'])
def addorder():
    data = json.loads(request.data)
    userid = int(data['userid'])
    courseid = int(data['couresid'])
    print('userid',userid)
    sum = 0
    orderno = str(int(time.time()))+str(userid)+str(random.randint(10000,99999))
    try:
        sql = "select * from course where id=%d"%courseid
        res = db.find(sql)
        sum += float(res['price'])
        # 添加详情表
        sql1 = "insert into orders(create_time, update_time, order_no, userid, courseid, number, price, tmoney, status, trans_no) "
        db.add(sql)
        # 添加订单表
        create_time = datetime.datetime.strftime(
            datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql2 = "insert into order1(number,price,create_time,status,usersid) values('%s','%s','%s',%d,%d)" % (
        orderno, sum, create_time, 1, userid)
        db.add(sql2)
        db.commit()
        return jsonify({'code':200,'msg':'ok'})
    except Exception as e:
        print('>>>>',e)
        db.rollback()
        return jsonify({'code':400,'msg':'错误'})
